package dao.impl;


import bean.OrderItem;

import dao.OrderItemDao;

import util.DBCon;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderItemDaoImpl implements OrderItemDao {
    @Override
    public List<OrderItem> getOrderItemsByOrderId(int orderId) {
        Connection con = DBCon.getConnection();
        if (con == null) {
            System.out.println("数据库连接失败");
            return null;
        }
        List<OrderItem> orderItemList = new ArrayList<>();
        try {
            PreparedStatement preparedStatement = con.prepareStatement("select * from table_order_item where order_id = ? ");
            preparedStatement.setInt(1, orderId);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(orderId);
                orderItem.setId(rs.getInt("order_item_id"));
                orderItem.setPrice(rs.getBigDecimal("price"));
                orderItem.setSeat(rs.getString("seat"));
//                System.out.println(orderItem);
                orderItemList.add(orderItem);
            }
            return orderItemList;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean addOrderItem(OrderItem orderItem) {
        Connection con = DBCon.getConnection();
        if (con == null) {
            System.out.println("连接数据库失败");
            return false;
        }
        try {
            PreparedStatement preparedStatement = con.prepareStatement("insert into table_order_item(order_id,seat,price)values(?,?,?)");
            preparedStatement.setInt(1, orderItem.getOrderId());
            preparedStatement.setString(2, orderItem.getSeat());
            preparedStatement.setBigDecimal(3, orderItem.getPrice());
            int addNum = preparedStatement.executeUpdate();
            if (addNum > 0) {
                System.out.println("成功添加" + addNum + "条数据");
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
